package mspbots.qbd.data.desktop;

import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import mspbots.qbd.data.BaseReceiver;
import mspbots.qbd.data.desktop.balancesheet.BalanceSheetDetail;
import mspbots.qbd.data.desktop.balancesheet.BalanceSheetDetailRepository;
import mspbots.qbd.data.desktop.balancesheet.BalanceSheetSummary;
import mspbots.qbd.data.desktop.balancesheet.BalanceSheetSummaryRepository;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import java.time.LocalDateTime;

/**
 * mspbots.data.sync.quickbooks.desktop.BalanceSheetReceiver
 *
 * @author Alex bob(https://github.com/vnobo)
 * @date Created by 2020/6/9
 */
@Log4j2
@Component
@RequiredArgsConstructor
public class BalanceSheetReceiver extends BaseReceiver {

    private final BalanceSheetDetailRepository detailRepository;
    private final BalanceSheetSummaryRepository summaryRepository;

    @RabbitListener(queues = "quick-books-desktop.BalanceSheet-summary.sync", concurrency = "6")
    public void processSummary(BalanceSheetSummary resultNode) {
        this.saveStandard(resultNode);
    }

    private void saveStandard(BalanceSheetSummary resultNode) {
        resultNode.setSyncTime(LocalDateTime.now());
        BalanceSheetSummary oldStandard = this.summaryRepository.findByTenantIdAndRowNumberAndTimePeriod(
                resultNode.getTenantId(), resultNode.getRowNumber(), resultNode.getTimePeriod()).block();
        if (!ObjectUtils.isEmpty(oldStandard) && oldStandard.getId() > 0) {
            resultNode.setId(oldStandard.getId());
        }
        this.summaryRepository.save(resultNode).block();
    }

    @RabbitListener(queues = "quick-books-desktop.BalanceSheet-detail.sync", concurrency = "6")
    public void processDetail(BalanceSheetDetail resultNode) {
        this.saveDetail(resultNode);
    }

    private void saveDetail(BalanceSheetDetail resultNode) {
        resultNode.setSyncTime(LocalDateTime.now());
        BalanceSheetDetail oldStandard = this.detailRepository.findByTenantIdAndRowNumberAndTimePeriod(
                resultNode.getTenantId(), resultNode.getRowNumber(), resultNode.getTimePeriod()).block();
        if (!ObjectUtils.isEmpty(oldStandard) && oldStandard.getId() > 0) {
            resultNode.setId(oldStandard.getId());
        }
        this.detailRepository.save(resultNode).block();
    }
}
